/* 
 * simple thread pool technique
 *
 * author: fulc0de(fullc0de@gmail.com)
 * source: Utilizing Thread Pools in Performance-Critical Applications, Blake Thompson, Intel Corp.
 *         http://www.intel.com/cd/ids/developer/asmo-na/eng/20481.htm?page=1&cid=sw:multicore005
 *
 */

#ifndef _THREADPOOL_H_
#define _THREADPOOL_H_	1

#include "PoolJob.h"


#define MAXQUEUE	3		// i don't know how many works waited for maximum performance 


class CThreadPool
{
private:
	CThreadPool();
	~CThreadPool();

/* DEFAULT_THREAD_NUM is default number of thread if m_MaxNumThreads does not passed into.
   m_hThread should be dynamically allocated by DEFAULT_THREAD_NUM or m_MaxNumThreads.
   */
#define DEFAULT_THREAD_NUM		5
	HANDLE	*m_hThread;
	
	CPoolJob **m_pQueue;

// synchronization object and handle
	HANDLE	hEmptySlot;
	HANDLE	hWorkToDo;
	HANDLE	hExit;
	
	CRITICAL_SECTION	m_CriticalSection;
	
	int		m_MaxNumThreads;

	int		m_nTopIndex;
	int		m_nBottomIndex;
	int		m_Thrdaddr;

	volatile LONG		m_nWorkInProgress;


public:

// Interfaces
	static CThreadPool* GetInstance();	
	void initPool(int);
	void destroyPool();
	bool registJob(CPoolJob *);
	
	
private:				// Internal Methods
	void DoWork();				// working module
	bool GetWork(CPoolJob **);

	static unsigned __stdcall ThreadFunc( void* pArg );

};


#endif